<template>
  <div class="container" :class="{'darkmode' : isDarkmode}">
    <div class="left">
      <el-card style="height: 90%; margin: auto">
      <div class="left-top">
        <div class="left-top-headPortrait">
          <img :src="avatar" alt="头像">
        </div>
        <el-button @click="logOutClick" class="left-top-logOut">登出</el-button>
      </div>
      <div class="left-bottom">
        <el-menu
          active-text-color="#409EFF"
          background-color="#ffffff"
          class="el-menu-vertical-demo"
          :default-active="activePath"
          text-color="#000000"
          router
        >
          <el-menu-item index="/personalCenter/collect">
            <el-icon><Star /></el-icon>
            <span>收藏记录</span>
          </el-menu-item>

          <el-menu-item index="/personalCenter/history">
            <el-icon><Clock /></el-icon>
            <span>历史记录</span>
          </el-menu-item>
          
          <el-sub-menu v-if="isAuthor" index="1">
            <template #title>
              <el-icon><Tickets /></el-icon>
              <span>作品管理</span>
            </template>

            <el-menu-item index="/personalCenter/manageArticles">
              <el-icon><Edit /></el-icon>
              <span>文章管理</span>
            </el-menu-item>

            <el-menu-item index="/personalCenter/publishArticles">
              <el-icon><DocumentAdd /></el-icon>
              <span>文章发布</span>
            </el-menu-item>
          </el-sub-menu>

          <el-menu-item v-else index="/personalCenter/creatorCertification">
            <el-icon><EditPen /></el-icon>
            <span>创作者认证</span>
          </el-menu-item>

          <el-menu-item index="/personalCenter/setting">
            <el-icon><Setting /></el-icon>
            <span>网站设置</span>
          </el-menu-item>
        </el-menu>

        <div @click="clickRollbackHome" class="left-bottom-rollbackHome">
          <el-icon size="30"><Back /></el-icon>
          <span class="left-bottom-rollbackHome-content">返回首页</span>
        </div>
      </div>
      </el-card>
    </div>
    <div class="right">
      <div class="right-container">
        <el-card style="width: 100%; height: 100%" shadow="always">
          <!-- 给子组件传递方法，这里主要是给创作者认证页面 -->
          <RouterView @auth-success="handleAuthSuccess" @update-article="handleUpdateArticle"></RouterView>
        </el-card>
      </div>
    </div>

    <!-- vue工具获取到最开始是false但是还是显示了,感觉没有配置正确 -->
    <LogOutDialog v-model="logOutDialogVisible" @close-dialog="closeDialog"></LogOutDialog>
  </div>
</template>

<script setup lang="ts">
import { RouterView, useRouter} from 'vue-router'
import LogOutDialog from './components/LogOutDialog.vue';
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

//### 数据定义 ###
const logOutDialogVisible = ref(false); //用于控制登出弹窗是否显示
const router = useRouter(); //创建路由
const isDarkmode = ref(false);  //是否开启夜间模式
const isAuthor = ref(false);  //是否为创作者
const activePath = ref('/personalCenter/collect') //默认选中的菜单
const avatar = ref('http://8.130.118.52:9000/images/headPortrait/defaultHead.png');  //头像

//### 方法定义 ###
// 为认证成功提供的方法，目标实现：通过代码打开菜单，同时刷新路由
const handleAuthSuccess = () => {
  isAuthor.value = true; // 切换菜单显示
  
  nextTick(() => {  // 需要 nextTick 等待 DOM 更新
    // 1. 设置激活路径 (必须匹配 el-menu-item 的 index)
    activePath.value = '/personalCenter/publishArticles';
    
    // 2. 手动展开父菜单（针对 el-sub-menu）
    const menuComponent = document.querySelector('.el-menu')?.__vue__;
    if (menuComponent) {
      // 打开 index="1" 的父菜单（对应你的 el-sub-menu）
      menuComponent.open('1'); 
      
      // 强制更新激活状态
      menuComponent.updateActiveIndex('/personalCenter/publishArticles');
    }
    
    // 3. 路由跳转
    router.push('/personalCenter/publishArticles');
  });

  ElMessage({
    message: '创作者，开始你的创作之旅吧！',
    type: 'success',
  })
};

//文章修改的方法
const handleUpdateArticle = (id:any) => {
  console.log("被调用了，，")
  isAuthor.value = true; // 切换菜单显示
  
  nextTick(() => {  // 需要 nextTick 等待 DOM 更新
    // 1. 设置激活路径 (必须匹配 el-menu-item 的 index)
    activePath.value = '/personalCenter/publishArticles';
    
    // 2. 手动展开父菜单（针对 el-sub-menu）
    const menuComponent = document.querySelector('.el-menu')?.__vue__;
    if (menuComponent) {
      // 打开 index="1" 的父菜单（对应你的 el-sub-menu）
      menuComponent.open('1'); 
      
      // 强制更新激活状态
      menuComponent.updateActiveIndex('/personalCenter/publishArticles');
    }
    
    // 3. 路由跳转并传参
    router.push({ name: 'publishArticles', query: { articleId: id }});
  });

  ElMessage({
    message: '请对应编辑需要修改的文章部分，并重新上传',
    type: 'success',
  })
}

//初始化函数
const initPersonalCenterView = () => {
  //在君子行为下，来到此处已经是认证过了，当然也是目前前期一个简化
  router.push('/personalCenter/collect')
}

function logOutClick() {
  console.log('我被点击了')
  logOutDialogVisible.value = true;
}

//点击返回首页
function clickRollbackHome() {
  router.push({
    name: 'home'
  });
}

//## 自定义事件方法
function closeDialog() {
	logOutDialogVisible.value = false;
}

//### 生命周期函数 ###
onMounted(() => {
  initPersonalCenterView();
  const head = window.localStorage.getItem('ten-seek-avatar')
  if(head) {
    avatar.value = head;
  }
  //夜间模式检查
  let darkmode = window.localStorage.getItem('tenSeekIsDarkmode');
  if(darkmode === 'true') {
    isDarkmode.value = true;
  }

  //是否为创作者
  const authoritiesJsonString = window.localStorage.getItem('ten-seek-privilege');

  if(authoritiesJsonString) {
    const authorities = JSON.parse(authoritiesJsonString);
    const creationArticle = authorities.find(item => item.authority === 'creation_article');  //查询权限中是否存在创作者
    isAuthor.value = creationArticle ? true : false;
  }
})
</script>

<style scoped lang="scss">
.container {
  display: flex;
  // background: chartreuse;
  justify-content: center;
  height: 100%;
  background: var(--base-color);
  color: var(--text-color);

  .left {
    // background: #c4cbcf;
    height: 100%;
    flex: 0.1;
    display: flex;
    flex-direction: column;
    padding-left: 20px;

    ::v-deep .el-card  {
      background: var(--base-color);
    }
    
    .left-top {
      flex: 2;
      // background: bisque;
      display: flex;
      flex-direction: column;
      align-items: center;

      .left-top-headPortrait {
        img {
          margin-top: 10px;
          margin-bottom: 20px;
          border-radius: 50%;
          width: 80px;       /* 固定宽度 */
          height: 80px;      /* 固定高度，与宽度相同 */
          object-fit: cover; /* 保证图片比例不变形 */
          display: block;    /* 避免行内元素的间隙问题 */
        }
      }

      .left-top-logOut {
        margin-bottom: 5px;
      }
    }

    .left-bottom {
      flex: 8;
      padding-top: 20px;
      // background: brown;

      /* 左侧底部菜单整体 */
      ::v-deep .el-menu {
        background: var(--base-color);
      }

      /* 左侧底部菜单图标 */
      ::v-deep .el-menu-item {
        color: var(--text-color);
      }

      /* 对应作品管理文字 */
      ::v-deep .el-sub-menu__title {
        color: var(--text-color);
      }

      /* 选中后菜单的颜色 */
      ::v-deep .is-active {
        color: #409EFF;
      }

      .left-bottom-rollbackHome {
        margin-top: 60px;
        display: flex;
        flex-direction: column;
        align-items: center; /* 垂直居中 */

        color: var(--text-color);

        .left-bottom-rollbackHome-content {
          margin-top: 2px;
        }
      }
    }
  }
  
  .right {
    // background: crimson;
    width: 100%;
    flex: 0.9;

    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */

    ::v-deep .el-card {
      background: var(--base-color);
      color: var(--text-color);
    }

    .right-container {
      height: 90%;
      width: 90%;
    }
  }
}
</style>